package com.shchuangzhi.smartguard.core;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by j_hu on 5/4/17.
 */

public class Clock {

    private static Calendar calendar;
    private static Job syncTimeJob;

    static {
        calendar = Calendar.getInstance();
        syncTimeJob = new Job(Consts.JOB_TIME_TICK, Consts.INTERVAL_TIME_TICK, new Job.JobExecutor() {
            @Override
            public Object Execute() {
                calendar.add(Calendar.MILLISECOND, 500);
                return null;
            }
        });
        syncTimeJob.start();
    }

    public static void sync(Date date) {
        calendar.setTime(date);
    }

    public static Calendar getCalendar() {
        return calendar;
    }

    public static Date now() {
        return calendar.getTime();
    }

    public static long getUnixTime() {
        return calendar.getTimeInMillis() / 1000;
    }

    public static long getCurrentInMillis() {
        return calendar.getTimeInMillis();
    }

    public static Date tomorrow() {
        Calendar c = Calendar.getInstance();
        c.setTime(now());
        c.add(Calendar.DATE, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:01");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(c.getTime());
        try {
            return sdf2.parse(format);
        }catch(Exception e) {
            return now();
        }
    }

    public static String nowStr() {
        return nowStr("yyyy-MM-dd HH:mm:ss");
    }

    public static String nowStr(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(now());
    }
}
